import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/dynamic_print.dart';
import 'package:thal/backstage/blueprint/user_print.dart';
import 'package:thal/backstage/control_room/dynamic_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/authentication_focus_curtain.dart';
import 'package:thal/backstage/toolkit/widgets/report_focus_curtain.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:thal/playbill/community_forum/dynamic_production.dart';
import 'package:thal/playbill/community_forum/ai_chat_production.dart';
import 'package:thal/playbill/community_forum/group_list_production.dart';
import 'package:thal/playbill/profile_saga/other_profile_production.dart';

part 'community_production.page.dart';

/// 社区页面
@PagePath('/community')
class CommunityProduction extends StatelessWidget {
  const CommunityProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$CommunityProductionQuery().call();

  @override
  Widget build(BuildContext context) {
    final dynamicRoom = GlobalStateProvider.dynamicRoomOf(context);
    final userRoom = GlobalStateProvider.userRoomOf(context);

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 固定的顶部标题
              _buildFixedHeader(),

              // 可滚动内容区域
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 两个功能按钮
                      _buildFeatureButtons(context),
                      24.h.heightBox,

                      // 动态列表
                      Observer(
                        builder: (_) {
                          final dynamics = dynamicRoom.dynamics;
                          return Column(
                            children:
                                dynamics.map((dynamic) {
                                  return _buildDynamicCard(
                                    context,
                                    dynamic,
                                    dynamicRoom,
                                    userRoom,
                                  );
                                }).toList(),
                          );
                        },
                      ),
                      50.h.heightBox,
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建固定顶部标题
  Widget _buildFixedHeader() {
    return Row(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
          child: Text('Community')
              .fontSize(30.sp)
              .textColor(ColorPalette.black)
              .carterOne(weight: FontWeight.w400),
        ),
      ],
    );
  }

  /// 构建功能按钮
  Widget _buildFeatureButtons(BuildContext context) {
    return Row(
      children: [
        // 群聊按钮
        Expanded(
          child: AspectRatio(
            aspectRatio: 171 / 125,
            child: ClipRRect(
              child: Image.asset(
                'assets/images/group-chat.png',
                fit: BoxFit.cover,
              ),
            ),
          ).withTapEffect(
            onTap: () {
              context.router.push(GroupListProduction.query());
            },
          ),
        ),
        16.w.widthBox,

        // AI 聊天按钮
        Expanded(
          child: AspectRatio(
            aspectRatio: 171 / 125,
            child: Image.asset('assets/images/ai-chat.png', fit: BoxFit.cover),
          ).withTapEffect(
            onTap: () {
              context.router.push(AiChatProduction.query());
            },
          ),
        ),
      ],
    );
  }

  /// 构建动态卡片
  Widget _buildDynamicCard(
    BuildContext context,
    DynamicPrint dynamic,
    DynamicRoom dynamicRoom,
    UserRoom userRoom,
  ) {
    final publisher = userRoom.fetchUserById(dynamic.userId);
    final currentUser = userRoom.fetchCurrentUser();

    return GestureDetector(
      onTap: () {
        context.router.push(DynamicProduction.query(dynamicId: dynamic.id));
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 16.h),
        decoration: BoxDecoration(
          color: ColorPalette.white,
          borderRadius: BorderRadius.circular(16.r),
          boxShadow: [
            BoxShadow(
              color: ColorPalette.black.withValues(alpha: 0.05),
              blurRadius: 8,
              offset: Offset(0, 2.h),
            ),
          ],
        ),
        child: AspectRatio(
          aspectRatio: 358 / 412,
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户信息栏
                _buildUserInfoSection(
                  context,
                  publisher,
                  dynamic.createdAt,
                  currentUser,
                  dynamic.userId,
                ).wrapHorizontal(16.w),
                12.h.heightBox,

                // 标题
                Text(
                      dynamic.title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                    .fontSize(16.sp)
                    .textColor(ColorPalette.black)
                    .arimo(weight: FontWeight.bold)
                    .wrapHorizontal(16.w),

                12.h.heightBox,

                // 图片/视频展示
                Expanded(
                  child: Stack(
                    children: [
                      // 图片/视频缩略图
                      Image.asset(
                        _getMediaUrl(dynamic),
                        fit: BoxFit.cover,
                        width: double.infinity,
                      ),
                      // 如果是视频，显示播放图标
                      if (dynamic.mediaType == 'video')
                        Positioned.fill(
                          child: Center(
                            child: Icon(
                              Icons.play_arrow_rounded,
                              size: 40.sp,
                              color: ColorPalette.white,
                            ),
                          ),
                        ),
                    ],
                  ),
                ),

                12.h.heightBox,

                // 底部互动按钮
                _buildActionButtons(
                  context,
                  dynamic,
                  dynamicRoom,
                  currentUser,
                ).wrapHorizontal(16.w),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建用户信息栏
  Widget _buildUserInfoSection(
    BuildContext context,
    UserPrint? publisher,
    DateTime createdAt,
    UserPrint? currentUser,
    String? dynamicUserId,
  ) {
    final timeAgo = _formatTimeAgo(createdAt);
    final isOwnPost = currentUser != null && currentUser.id == dynamicUserId;

    // 获取关注管理器
    final followRoom = GlobalStateProvider.followRoomOf(context);

    return Row(
      children: [
        // 用户头像
        GestureDetector(
          onTap:
              isOwnPost
                  ? null
                  : () {
                    // 跳转到他人主页
                    context.router.push(
                      OtherProfileProduction.query(userId: dynamicUserId ?? ''),
                    );
                  },
          child: Container(
            width: 44.w,
            height: 44.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20.r),
              border: Border.all(
                color: ColorPalette.black.withValues(alpha: 0.1),
                width: 1.w,
              ),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(20.r),
              child: Image.asset(
                publisher?.avatar ?? AssetManifest.avatar1,
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),

        12.w.widthBox,

        // 用户名和时间
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                    publisher?.username ?? 'Unknown',
                    style: TextStyle(height: 1.57),
                  )
                  .fontSize(14.sp)
                  .textColor(ColorPalette.black)
                  .arimo(weight: FontWeight.w700),
              2.h.heightBox,
              Text(timeAgo)
                  .fontSize(12.sp)
                  .textColor(ColorPalette.black.withValues(alpha: 0.6))
                  .arimo(),
            ],
          ),
        ),

        // Follow 按钮
        if (!isOwnPost)
          Observer(
            builder: (_) {
              // 重新检查关注状态
              final currentIsFollowing =
                  currentUser != null &&
                  dynamicUserId != null &&
                  followRoom.isFollowing(currentUser.id, dynamicUserId);

              return SizedBox(
                width: 90.w,
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color:
                        currentIsFollowing
                            ? ColorPalette.white
                            : ColorPalette.blue1,
                    borderRadius: BorderRadius.circular(20.r),
                    border:
                        currentIsFollowing
                            ? Border.all(color: ColorPalette.blue1, width: 1.w)
                            : null,
                  ),
                  child: Text(
                        currentIsFollowing ? 'Followed' : 'Follow',
                        textAlign: TextAlign.center,
                      )
                      .fontSize(12.sp)
                      .textColor(
                        currentIsFollowing
                            ? ColorPalette.blue1
                            : ColorPalette.white,
                      )
                      .arimo(weight: FontWeight.w600),
                ),
              ).withTapEffect(
                onTap: () {
                  if (currentUser == null) {
                    AuthenticationSpotlight.illuminate(context);
                    return;
                  }
                  // 不能关注自己
                  if (currentUser.id == dynamicUserId) {
                    StageWhisper.caution('You cannot follow yourself');
                    return;
                  }

                  // 切换关注状态
                  if (dynamicUserId == null) return;

                  if (currentIsFollowing) {
                    final success = followRoom.performUnfollow(
                      currentUser.id,
                      dynamicUserId,
                    );
                    if (success) {
                      StageWhisper.cheer('Unfollowed successfully');
                    } else {
                      StageWhisper.lament('Failed to unfollow');
                    }
                  } else {
                    final success = followRoom.performFollow(
                      currentUser.id,
                      dynamicUserId,
                    );
                    if (success) {
                      StageWhisper.cheer('Followed successfully');
                    } else {
                      StageWhisper.lament('Failed to follow');
                    }
                  }
                },
              );
            },
          ),
      ],
    );
  }

  /// 构建互动按钮
  Widget _buildActionButtons(
    BuildContext context,
    DynamicPrint dynamic,
    DynamicRoom dynamicRoom,
    UserPrint? currentUser,
  ) {
    final isLiked =
        currentUser != null && dynamic.likes.contains(currentUser.id);

    return Row(
      children: [
        // 点赞按钮
        Container(
          padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 12.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15.r),
            border: Border.all(color: const Color(0x30999999), width: 1.w),
          ),
          child: Row(
            children: [
              Image.asset(
                isLiked ? AssetManifest.like : AssetManifest.unlike,
                width: 16.w,
                height: 16.w,
                color: isLiked ? ColorPalette.pink : ColorPalette.black,
              ),
              6.w.widthBox,
              Text(
                '${dynamic.likes.length}',
              ).fontSize(12.sp).textColor(ColorPalette.black).arimo(),
            ],
          ),
        ).withTapEffect(
          onTap: () {
            if (currentUser == null) {
              AuthenticationSpotlight.illuminate(context);
              return;
            }
            dynamicRoom.toggleLike(dynamic.id, currentUser.id);
          },
        ),

        16.w.widthBox,

        // 评论按钮
        Container(
          padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 12.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15.r),
            border: Border.all(color: const Color(0x30999999), width: 1.w),
          ),
          child: Row(
            children: [
              Image.asset(
                AssetManifest.comment,
                width: 16.w,
                height: 16.w,
                color: ColorPalette.black,
              ),
              6.w.widthBox,
              Text(
                '${dynamic.comments.length}',
              ).fontSize(12.sp).textColor(ColorPalette.black).arimo(),
            ],
          ),
        ).withTapEffect(
          onTap: () {
            context.router.push(DynamicProduction.query(dynamicId: dynamic.id));
          },
        ),

        const Spacer(),

        // 举报按钮
        Image.asset(
          AssetManifest.report,
          width: 20.w,
          height: 20.w,
          color: const Color(0xFF4C4C4C),
        ).withTapEffect(
          onTap: () {
            ReportAccusation.raise(
              context,
              targetId: dynamic.id,
              targetType: 'dynamic',
              onReportSubmitted: (reason) {
                // 删除动态
                dynamicRoom.deleteDynamic(dynamic.id);
                StageWhisper.cheer('Report submitted successfully');
              },
            );
          },
        ),
      ],
    );
  }

  /// 获取媒体URL（图片或视频缩略图）
  String _getMediaUrl(DynamicPrint dynamic) {
    if (dynamic.mediaUrls.isEmpty) {
      return AssetManifest.panda;
    }

    // 如果是视频类型且有缩略图，使用缩略图
    if (dynamic.mediaType == 'video' &&
        dynamic.thumbnailUrls.isNotEmpty &&
        dynamic.thumbnailUrls[0] != null) {
      return dynamic.thumbnailUrls[0]!;
    }

    // 否则使用第一张图片
    return dynamic.mediaUrls[0];
  }

  /// 格式化时间差
  String _formatTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays} Days Ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} Hours Ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} Minutes Ago';
    } else {
      return 'Just Now';
    }
  }
}
